package cn.ecut.servlet.user;

import cn.ecut.pojo.Role;
import cn.ecut.pojo.User;
import cn.ecut.service.role.RoleService;
import cn.ecut.service.role.RoleServiceImpl;
import cn.ecut.service.user.UserService;
import cn.ecut.service.user.UserServiceImpl;
import cn.ecut.util.Constants;
import cn.ecut.util.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author ruanxin
 */
//实现方法复用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("savepwd".equals(method)) {
            this.updateUserPwd(req, resp);
        } else if ("pwdmodify".equals(method)) {
            this.checkOldPwd(req, resp);
        } else if ("query".equals(method)) {
            this.query(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改密码
    public void updateUserPwd(HttpServletRequest req, HttpServletResponse resp) {
        boolean flag = false;
        //从Session中拿id
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpwd = req.getParameter("newpassword");
        System.out.println("UserServlet" + newpwd);

        if (o != null && newpwd != null) {
            UserService userService = new UserServiceImpl();
            flag = userService.updateUserPassword(((User) o).getId(), newpwd);
            if (flag) {
                req.setAttribute("messgae", "修改密码成功，请重新登录");
                //修改成功，移除Session重新登录
                req.getSession().removeAttribute(Constants.USER_SESSION);

            } else {
                req.setAttribute("messgae", "密码修改失败");
            }
        } else {
            req.setAttribute("messgae", "新密码有问题");
        }

        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //验证旧密码
    public void checkOldPwd(HttpServletRequest req, HttpServletResponse resp) {
        //从Session获取对象
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map：结果集
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (o == null) {//Session失效或者过期了
            resultMap.put("result", "sessionerror");
        } else if (StringUtils.isNullOrEmpty(oldpassword)) {//输入密码为空
            resultMap.put("result", "error");
        } else {
            String userPassword = ((User) o).getUserPassword();
            if (userPassword.equals(oldpassword)) {
                resultMap.put("result", "true");
            } else {
                resultMap.put("result", "false");
            }
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿里巴巴的JSON工具类，转换格式
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //查询用户 重点、难点
    public void query(HttpServletRequest req, HttpServletResponse resp) {

        //从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

        List<User> userList = null;


        if (queryUserName == null) {
            queryUserName = "";
        }

        if (temp != null && !temp.equals("")) {
            queryUserRole = Integer.parseInt(temp);//给查询赋值
            System.out.println("this queryUserRole" + queryUserRole);
        }

        //获取用户列表
        UserService userService = new UserServiceImpl();
        //第一次走这个请求，一定是第一页，页面大小固定
        int pageSize = 5;//可以写到配置文件
        int currentPageNo = 1;

        if (pageIndex != null) {
            try {
                currentPageNo = Integer.parseInt(pageIndex);
            } catch (NumberFormatException e) {
                try {
                    resp.sendRedirect("error.jsp");
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
            }
        }
        //总数量表
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页数
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(pageSize);
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setTotalCount(totalCount);

        int totalPageCount = pageSupport.getTotalPageCount();

        //控制首页和尾页
        //如果页面要小于1 就显示第一页
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        System.out.println("UserServlet:    "+userList.toString());
        req.setAttribute("userList", userList);
        List<Role> roleList = null;
        RoleService roleService = new RoleServiceImpl();
        roleList = roleService.getRoleList();

        req.setAttribute("userList",userList);
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);
        System.out.println("UserServlet queryUserRole:" +queryUserRole);

        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
